<template>
	<view class="container">
		<view class="form-item">
			<label>姓名</label>
			<input type="nickname" placeholder="请输入姓名" @input="updateName" />
		</view>
		<view class="form-item">
			<label>性别</label>
			<radio-group @change="updateSex">
				<label class="radio">
					<radio value="男" checked /><text>男</text>
				</label>
				<label class="radio">
					<radio value="女" /><text>女</text>
				</label>
			</radio-group>
		</view>
		<view class="form-item">
			<label>电话</label>
			<input type="number" placeholder="请输入电话" @input="updatePhone" />
		</view>
		<view class="form-item">
			<label>所在城市</label>
			<position-picker @update-region="regionChange"></position-picker>
		</view>
		??????????所在小区??????????
		<view class="form-item">
			<label>详细地址</label>
			<input type="text" placeholder="请输入详细地址" @input="updatePosition" />
		</view>
		<view class="form-item">
			<label>身份证号</label>
			<input type="idcard" placeholder="请输入身份证号" @input="updateIdCard" />
		</view>
		<view class="form-item">
			<label>开户行</label>
			<input type="text" placeholder="请输入银行名称" @input="updateBankName" />
		</view>
		<view class="form-item">
			<label>银行卡号</label>
			<input placeholder="请输入银行卡号" @input="updateBankCard" />
		</view>
		<view class="form-item">
			<label>请上传身份证反正面照片</label>
			<uni-section title="只选择图片" type="line">
				<view class="example-body">
					<uni-file-picker limit="2" title="最多选择2张图片" @select="handleIdSelect"
						@delete="handleIdDelete"></uni-file-picker>
				</view>
			</uni-section>
		</view>
		<button type="primary" @click="submitForm" @tap="submit">提交申请</button>
		<button type="primary" @click="test">提交申请</button>
	</view>
</template>

<script setup>
	import http from '../../utils/http';
	// 提取字段
	const applicationContent = ref({
		applicationId: "",
		applicationTime: "",
		applicationType: "bulter",
		currentType: getApp().globalData.user.identity,
		openid: getApp().globalData.user.openid, // 商家的openid
		name: '', // 姓名
		sex: '男', // 性别
		phone: '', // 联系电话
		region: '', // 所在城市
		position: '', // 详细地址
		longitude: '', // 经度
		latitude: '', // 纬度
		idCard: '', // 身份证号
		bankName: '', // 开户行
		bankCard: '', // 银行卡号
		idImage: [],
		applicationStatus:"pending"
	});
	const image = ref({
		idCard: [], //身份证正反面照片
	})
	// 姓名
	function updateName(e) {
		applicationContent.value.name = e.target.value;
	}
	// 性别
	function updateSex(e){
		applicationContent.value.sex = e.target.value;
	}
	// 电话
	function updatePhone(e) {
		applicationContent.value.phone = e.target.value;
	}
	// 所在区域
	function regionChange(e) {
		// console.log("position", e[0] + "-" + e[1] + "-" + e[2])
		applicationContent.value.region = e[0] + "-" + e[1] + "-" + e[2]
	}
	// 详细地址
	function updatePosition(e) {
		applicationContent.value.position = e.target.value;
	}

	function updateIdCard(e) {
		applicationContent.value.idCard = e.target.value;
	}
	//身份证正面照片
	function handleIdSelect(e) {
		if (e.tempFiles.length == 0) {
			return;
		}
		for (let i in e.tempFiles) {
			image.value.idCard.push(e.tempFiles[i])
		}

	}

	function handleIdDelete(e) {
		console.log("delete", e)
		image.value.idCard.splice(e.index, 1); // 移除数组中对应的文件
	}

	function updateBankName(e) {
		applicationContent.value.bankName = e.target.value
	}

	function updateBankCard(e) {
		applicationContent.value.bankCard = e.target.value
	}

	// 上传文件函数
	async function uploadFile(file, fileType) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://localhost:8080/utils/upLoadFile',
				filePath: file.path,
				name: 'file', // 文件字段名
				formData: {
					"filename": generateApplicationId(true, file),
					"applicationId": applicationContent.value.applicationId,
					"type": "butlerApplication"
				},
				success: (uploadRes) => {
					const res = JSON.parse(uploadRes.data).data;
					applicationContent.value.idImage.push(res)
					resolve();
				},
				fail: (error) => {
					console.log('上传失败', error);
					reject(error);
				}
			});
		});
	}

	function generateApplicationId(flag, file) {
		const now = new Date();
		const year = now.getFullYear().toString().padStart(4, '0'); // 获取年份并转换为四位数
		const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并转换为两位数
		const day = now.getDate().toString().padStart(2, '0'); // 获取日期并转换为两位数
		const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并转换为两位数
		const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并转换为两位数
		const seconds = now.getSeconds().toString().padStart(2, '0'); // 获取秒并转换为两位数
		const milliseconds = now.getMilliseconds().toString().padStart(3, '0'); // 获取毫秒并转换为三位数

		if (flag == true) {
			// 添加文件类型或文件名作为唯一标识符
			const fileType = file.type || 'unknown'; // 文件类型
			const fileName = file.name || 'unknown'; // 文件名

			return `${year}${month}${day}${hours}${minutes}${seconds}_${milliseconds}_${fileType}_${fileName}`;
		} else
			return `${year}${month}${day}${hours}${minutes}${seconds}_${milliseconds}`;
	}

	function generateTime() {
		const now = new Date();
		const year = now.getFullYear().toString().padStart(4, '0'); // 获取年份并转换为四位数
		const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并转换为两位数
		const day = now.getDate().toString().padStart(2, '0'); // 获取日期并转换为两位数
		const hours = now.getHours().toString().padStart(2, '0'); // 获取小时并转换为两位数
		const minutes = now.getMinutes().toString().padStart(2, '0'); // 获取分钟并转换为两位数
		const seconds = now.getSeconds().toString().padStart(2, '0'); // 获取秒并转换为两位数
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	async function submit() {
		try {
			applicationContent.value.applicationId = generateApplicationId(false);
			applicationContent.value.applicationTime = generateTime();
			console.log("applicationContent", applicationContent.value);
			// 上传身份证图片
			const idCardPromises = image.value.idCard.map(idCardFile => uploadFile(idCardFile, 'idCard'));



			// 等待所有上传操作完成
			await Promise.all([...idCardPromises]);

			// 所有上传操作完成后，调用 http.request
			const responseData = await http.request({
				url: "/api/application/insert_application",
				method: "POST",
				data: {
					application: applicationContent.value
				}
			});
			console.log("提交成功", responseData.data);
		} catch (err) {
			// 在这里处理上传文件过程中的错误
			console.log("上传文件失败", err);
		}
	}

	function test() {
		console.log("test", applicationContent.value)
		console.log("golbal", getApp().globalData.openid)
	}
</script>

<style lang="scss" scoped>
@import "./application.scss";
</style>